import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

// GET /api/customers/:id - 获取单个客户
export async function GET(
    request: NextRequest,
    { params }: { params: { id: string } }
) {
    try {
        const customer = await prisma.customer.findUnique({
            where: { id: params.id },
            include: { orders: true }
        })

        if (!customer) {
            return NextResponse.json(
                { success: false, error: 'Customer not found' },
                { status: 404 }
            )
        }

        return NextResponse.json({
            success: true,
            data: customer
        })
    } catch (error) {
        console.error('Error fetching customer:', error)
        return NextResponse.json(
            { success: false, error: 'Failed to fetch customer' },
            { status: 500 }
        )
    }
}

// PUT /api/customers/:id - 更新客户
export async function PUT(
    request: NextRequest,
    { params }: { params: { id: string } }
) {
    try {
        const body = await request.json()

        const { nickname } = body

        if (!nickname) {
            return NextResponse.json(
                { success: false, error: 'Missing required field: nickname' },
                { status: 400 }
            )
        }

        const customer = await prisma.customer.update({
            where: { id: params.id },
            data: { nickname }
        })

        return NextResponse.json({
            success: true,
            data: customer
        })
    } catch (error: any) {
        console.error('Error updating customer:', error)

        if (error.code === 'P2025') {
            return NextResponse.json(
                { success: false, error: 'Customer not found' },
                { status: 404 }
            )
        }

        return NextResponse.json(
            { success: false, error: 'Failed to update customer' },
            { status: 500 }
        )
    }
}

// DELETE /api/customers/:id - 删除客户
export async function DELETE(
    request: NextRequest,
    { params }: { params: { id: string } }
) {
    try {
        await prisma.customer.delete({
            where: { id: params.id }
        })

        return NextResponse.json({
            success: true,
            message: 'Customer deleted successfully'
        })
    } catch (error: any) {
        console.error('Error deleting customer:', error)

        if (error.code === 'P2025') {
            return NextResponse.json(
                { success: false, error: 'Customer not found' },
                { status: 404 }
            )
        }

        return NextResponse.json(
            { success: false, error: 'Failed to delete customer' },
            { status: 500 }
        )
    }
}
